package cn.adelyn.base.rbac.dao;

import cn.adelyn.base.rbac.constant.RbacCacheNames;
import cn.adelyn.base.rbac.dao.mapper.MenuMapper;
import cn.adelyn.base.rbac.dao.mapper.UserTypePermissionMapper;
import cn.adelyn.base.rbac.pojo.model.MenuModel;
import cn.adelyn.base.rbac.pojo.model.UserTypePermissionModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PermissionDAOService {

    @Autowired
    MenuMapper menuMapper;

    @Autowired
    UserTypePermissionMapper userTypePermissionMapper;

    /**
     * 获取该uri所需的permission
     */
    @Cacheable(cacheNames = RbacCacheNames.URI_PERMISSION, key = "#uri + ':' + #method")
    public String getUriPermission(String uri, Integer method) {

        QueryWrapper<MenuModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(MenuModel::getUri, uri)
                .eq(MenuModel::getMethod, method)
                .last("limit 1");

        return menuMapper.getUriPermission(queryWrapper);
    }

    @Cacheable(cacheNames = RbacCacheNames.USER_PERMISSIONS, key = "#userType")
    public List<String> listAllPermissionByUserType(Integer userType) {

        QueryWrapper<UserTypePermissionModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(UserTypePermissionModel::getUserType, userType);

        return userTypePermissionMapper.listAllPermissionByUserType(queryWrapper);
    }

    @Caching(evict = {
            @CacheEvict(cacheNames = RbacCacheNames.URI_PERMISSION, key = "#uri + ':' + #method"),
            @CacheEvict(cacheNames = RbacCacheNames.USER_PERMISSIONS, key = "#userType")
    })
    public void clearUserPermissionsCache(Long userId, Integer userType) {
    }
}
